<?php

namespace App\Mini;

use App\Http\Controllers\Controller;
use App\Models\Mini;
use Illuminate\Http\Request;
use Houdunwang\Mini\Auth;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\Client\RequestException;
use WeChatService;

/**
 * 小程序登录
 * @package App\Mini
 */
class AuthController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @param Mini $mini
     * @param mixed $code
     * @return mixed
     * @throws RequestException
     */
    public function login(Request $request, Mini $mini, string $code)
    {
        $info = Auth::init($mini)->getOpenidByCode($code);
        $data = array_merge($info, $request->input());
        $token = WeChatService::saveUser($data)->createToken('auth')->plainTextToken;
        return $this->message('登录成功', ['token' => $token]);
    }

    /**
     * 获取用户微信openid/unionid
     * @param Request $request
     * @param Mini $mini
     * @param string $code
     * @return void
     * @throws RequestException
     * @throws BindingResolutionException
     */
    public function openid(Request $request, Mini $mini, string $code)
    {
        $info = Auth::init($mini)->getOpenidByCode($code);
        return $this->message('用户微信资料获取成功', $info);
    }
}
